package com.wwm.makerandroid.makerandroid.View.Fragment;


import static com.wwm.makerandroid.makerandroid.Utils.DateUtil.getDatePickerTime;
import static com.wwm.makerandroid.makerandroid.Utils.DateUtil.getTimePickerTime;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;


import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import com.lipiao.makerandroid.R;
import com.wwm.makerandroid.makerandroid.Bean.RespondBean.MessageBean;
import com.wwm.makerandroid.makerandroid.Bean.RespondBean.UserDto;
import com.wwm.makerandroid.makerandroid.Bean.ViewBean.ApplyBean;
import com.wwm.makerandroid.makerandroid.MainActivity;
import com.wwm.makerandroid.makerandroid.Utils.DateUtil;
import com.wwm.makerandroid.makerandroid.Utils.DivisionModel;
import com.wwm.makerandroid.makerandroid.Utils.Divisions;
import com.wwm.makerandroid.makerandroid.Utils.HttpUtil;
import com.wwm.makerandroid.makerandroid.Utils.MyBeanUtils;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import top.defaults.view.Division;
import top.defaults.view.DivisionPickerView;


//原始的四个碎片自带缓存 无需懒加载 也不会重复加载数据
public class ApplyFragment extends Fragment {

    static String userNumber;//账号

    String TAG = "ApplyFragment";
    RadioGroup typeRG;
    Button startBt;
    Button endBt;
    EditText reasonText;
    Button destinationText;
    Spinner apprvoerSp;
    Button submitApplyBt;
    View rootView;
    DivisionPickerView divisionPicker;
    //获取content 这个可以直接 getContent得到  开始不知道 绕了个大弯才得到
    MainActivity mainActivity;
    //    static Context context;
    ApplyBean applyBean = new ApplyBean();
    //    涉及选择审批人这块都是屎
    HashMap<String, String> approverMap;
    String[] approverArray;
    List approvers;//用户可选请假的审批人
    String approver;//用户实际选择请假的审批人
//    交通工具组
    RadioGroup vehicleRG;
//    交通工具
    RadioButton radioButton;
////班次的标题框
    TextView banciName;
//班次的文本框
    EditText banciText;
//    出发地是有疫情
    RadioButton rbStart;//
    //   目的地是有疫情
    RadioButton rbDestion;
//    出发地
    EditText editText;

    public ApplyFragment newInstance(String userNumber, MainActivity context) {
        ApplyFragment fragment = new ApplyFragment();
        Bundle bundle = new Bundle();
        bundle.putString("userNumber", userNumber);
        this.userNumber = userNumber;
        Intent intent = new Intent(context, MainActivity.class);
//  this.approvers = intent.getStringExtra(approvers);
        applyBean.setUserNumber(userNumber);
        mainActivity = context;
        fragment.setArguments(bundle);
        return fragment;
    }

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        context = getBaseContext();


    }

    //Button button
//创建碎片视图
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.apply_card_item, container, false);
        initView();
        divisionPicker=rootView.findViewById(R.id.divisionPicker);
        destinationText=rootView.findViewById(R.id.text_diqu);
        List<DivisionModel> divisions= Divisions.get("");
        divisionPicker.setDivisions(divisions);
//        为地区选择器添加事件监听 当地区选择器改变时 为地区文本框赋值
        divisionPicker.setOnSelectedDateChangedListener(division ->
                destinationText.setText(Division.Helper.getCanonicalName(division)));
//       为地区文本添加监听 当点击设置地区选择器是否显示
//        0显示  8不显示
//        divisionPicker->divisionPicker.setVisibility(8-divisionPicker.getVisibility())
        destinationText.setOnClickListener(view -> divisionPicker
                .setVisibility(8-divisionPicker.getVisibility()));
        banciText=rootView.findViewById(R.id.et_banci);
        banciName=rootView.findViewById(R.id.tv_banci);
        rbStart=rootView.findViewById(R.id.start1);
        rbDestion=rootView.findViewById(R.id.dest1);
        editText=rootView.findViewById(R.id.text_start);

        //    assert getArguments() != null;//判空处理
//       userNumber A= getArguments().getString("userNumber");//获取账号
        return rootView;
    }

    //实例化控件
    public void initView() {
        typeRG = rootView.findViewById(R.id.rg);
        vehicleRG=rootView.findViewById(R.id.rgv1);
        vehicleRG.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                System.out.println(i);
                if(i==R.id.rbv1){
                    banciName.setText("请输入航班");
                    banciName.setVisibility(View.VISIBLE);
                    banciText.setVisibility(View.VISIBLE);
                }
                else
                if(i==R.id.rbv2){
                    banciName.setText("请输入班次");
                    banciName.setVisibility(View.VISIBLE);
                    banciText.setVisibility(View.VISIBLE);
                }
                else
                if(i==R.id.rbv4){
                    banciName.setText("请输入车牌");
                    banciName.setVisibility(View.VISIBLE);
                    banciText.setVisibility(View.VISIBLE);
                }
                else{
                    banciName.setVisibility(View.GONE);
                    banciText.setVisibility(View.GONE);
                }




            }
        });

                 reasonText = rootView.findViewById(R.id.et_reason);
        destinationText=rootView.findViewById(R.id.text_diqu);
        startBt = rootView.findViewById(R.id.bt_start);
        endBt = rootView.findViewById(R.id.bt_end);
//        approverBt = rootView.findViewById(R.id.);
        submitApplyBt = rootView.findViewById(R.id.bt_submitApply);
        apprvoerSp = rootView.findViewById(R.id.spinner);

        //添加点击监听
        startBt.setOnClickListener(mOnClickListener);
        endBt.setOnClickListener(mOnClickListener);

//        submitApplyBt.setOnClickListener(mOnClickListener);
        //调用接口查询 该用户有哪些审批人

        Call<MessageBean> call = HttpUtil.getUserService().getUserAllapprovers(userNumber);
        call.enqueue(new Callback<MessageBean>() {
            @Override
            public void onResponse(Call<MessageBean> call, Response<MessageBean> response) {
                approvers = (List) response.body().getData();
                //处理数据
                initSpinner();
            }

            @Override
            public void onFailure(Call<MessageBean> call, Throwable t) {

            }
        });


        submitApplyBt.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {

//验证数据
//todo 验证开始时间是否大于现在时间（虽然在打开选择开始时间对话框时已经设置过时间范围，
// 但是用户可以打开时间选择对话框后等很久再选开始时间 这样就会选择出比当前时间要早的错误时间）

// 是否比结束时间小
                applyBean.setApproverId(approver);
                applyBean.setDestination(destinationText.getText().toString());
//                applyBean.setType(Integer.valueOf(typeRG.getCheckedRadioButton().getTag().toString()));
                //请假类型和交通工具类型 只截取第一个字符 就是对应的数字
//                请假类型
                RadioButton applyTypeButton= (RadioButton) rootView.findViewById(typeRG.getCheckedRadioButtonId());
                String applyType = applyTypeButton.getText().toString().substring(0, 1);
                applyBean.setType(Integer.valueOf(applyType));
//              交通工具类型
                radioButton = (RadioButton) rootView.findViewById(vehicleRG.getCheckedRadioButtonId());
                String vehicle = radioButton.getText().toString().substring(0, 1);
                applyBean.setVehicle(vehicle);

                applyBean.setOutDate(startBt.getText().toString() + ":" + "00");
                applyBean.setExpectedReturnDate(endBt.getText().toString() + ":" + "00");
                applyBean.setReason(reasonText.getText().toString());
//                新增
                applyBean.setStartName(editText.getText().toString());
                applyBean.setBanci(banciText.getText().toString());
                applyBean.setStartYiqing(rbStart.isChecked());
                applyBean.setDestinationYiqing(rbDestion.isChecked());
                submitApply(applyBean);
            }
        });


    }
//提交请假申请


    private View.OnClickListener mOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.bt_start://打开日期选择对话框

                    showDateDialog(v, startBt, "开始");
                    break;
                case R.id.bt_end://结束日期
                    showDateDialog(v, endBt, "结束");
                    break;

                default:
                    break;

            }
        }


    };


    //打开对话框 //todo 抽象成的方法
    private void showDateDialog(View view, Button button, String title) {

        AlertDialog.Builder builder = new AlertDialog.Builder(mainActivity);
        final AlertDialog dialog = builder.create();
        View dialogView = View.inflate(mainActivity, R.layout.bg_dialog_date, null);
        DatePicker datePicker = dialogView.findViewById(R.id.data_picker);
        TimePicker timePicker = dialogView.findViewById(R.id.time_picker);
        Button cancleBt = dialogView.findViewById(R.id.tv_data_dialog_cancel);
        Button doneBt = dialogView.findViewById(R.id.tv_data_dialog_done);
        TextView tv = dialogView.findViewById(R.id.tv_pickdatetime);
        timePicker.setIs24HourView(true);
        tv.setText("请选择" + title + "时间");

        //判断是选择开始时间还是结束时间  这一段可以不要
        if (button == startBt) {
            //选择开始时间 范围为 大于现在时间小于结束时间
            datePicker.setMinDate(System.currentTimeMillis());
            String endTime = null;
//            fixme 日期转换工具类问题
            try {
                endTime = DateUtil.timeStampDate2(endBt.getText().toString());
            } catch (Exception e) {
                System.out.println(endBt.getText().toString());
            }
            if (endTime != null) {
                datePicker.setMaxDate(Long.parseLong(endTime));
            }
        }


        cancleBt.setOnClickListener(view1 -> dialog.dismiss());
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
        doneBt.setOnClickListener(dialogView1 -> {
//            button.setText(DatedatePicker.getDrawingTime());
            button.setText(datePicker.getYear() + "-" + getDatePickerTime(datePicker)+ " " + getTimePickerTime(timePicker));

            dialog.dismiss();
        });
        dialog.setView(dialogView);
        dialog.show();
    }


    private void submitApply(ApplyBean applyBean) {
        Gson gson = new Gson();

        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), gson.toJson(applyBean));
        Call<MessageBean> call = HttpUtil.getUserService().addapply(requestBody);
        call.enqueue(new Callback<MessageBean>() {
            @Override
            public void onResponse(Call<MessageBean> call, Response<MessageBean> response) {
//                Log.d(TAG, "onResponse: " + response.body().getMessage());
                Object strBack = null;
                try {
                    strBack = response.body().getData();

                    Map resmap = MyBeanUtils.getObjectToMap(strBack);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                System.out.println(strBack);
                //获取到响应
                if (response.body().isSuccess()) {
                    Toast.makeText(mainActivity, "提交申请成功!", Toast.LENGTH_LONG).show();

                } else {
                    Toast.makeText(mainActivity, "提交失败!" + strBack, Toast.LENGTH_LONG).show();
                }
            }

            @Override
            public void onFailure(Call<MessageBean> call, Throwable t) {
                Toast.makeText(mainActivity, t.getMessage(), Toast.LENGTH_LONG).show();
                Log.d(TAG, "onResponse: error");
                Log.d(TAG, t.getMessage());
            }
        });

    }





    //获得当前用户的审批人员 并添加到下拉框

    private void initSpinner() {
        approverMap = new HashMap<>();
        if (approvers != null) {
//            Gson gson = new Gsonbuilder.enableComplexMapKeySerialization().create();
            Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();
            for (Object temp : approvers
            ) {

                String jsonString = gson.toJson(temp);
                UserDto userDto = gson.fromJson(jsonString, UserDto.class);

                approverMap.put(userDto.getName(), userDto.getId());
            }
        }
        approverArray = approverMap.keySet().toArray(new String[approverMap.size()]);
        //声明一个下拉列表的数组适配器
        ArrayAdapter<String> starAdapter = new ArrayAdapter<String>((Context) mainActivity, R.layout.item_select, approverArray);
        //设置下拉框的标题，不设置就没有难看的标题了
        apprvoerSp.setPrompt("请选择审批人");
        //设置下拉框的数组适配器
        apprvoerSp.setAdapter(starAdapter);
        //设置下拉框默认的显示第一项
        apprvoerSp.setSelection(0);
        //给下拉框设置选择监听器，一旦用户选中某一项，就触发监听器的onItemSelected方法
        apprvoerSp.setOnItemSelectedListener(new MySelectedListener());
    }

    class MySelectedListener implements AdapterView.OnItemSelectedListener {

        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            approver = approverMap.get(approverArray[i]);
        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {

        }
    }

}
